package struts.ext.returntype.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts.action.ActionForward;

public class DownloadHandler implements Handler {

	@Override
	public ActionForward handle(HttpServletRequest request,
			HttpServletResponse response, Object retValue) throws Exception {
		
		
		if(retValue instanceof File){
			File file = (File)retValue;
			
			if (file.exists()) {
	            if (file.isDirectory()) {
	                throw new IOException("File '" + file + "' exists but is a directory");
	            }
	            if (file.canRead() == false) {
	                throw new IOException("File '" + file + "' cannot be read");
	            }
	        } else {
	            throw new FileNotFoundException("File '" + file + "' does not exist");
	        }
			
			response.setCharacterEncoding("utf-8");
			//在filename两边加上引号，解决在firefox下下载时不显示x扩展名的bug
			response.setHeader("Content-Disposition", "attachment; filename=\"" + 
					new String(file.getName().getBytes(), "iso-8859-1") + "\"");
			InputStream is = new FileInputStream(file);
			OutputStream os = response.getOutputStream();
			try{
				byte[] b=new byte[1024];
				int i=0;
				
				while((i=is.read(b))!=-1){
					os.write(b, 0, i);
					i=0;
				}
				os.flush();
			}catch(Exception e){
				throw new Exception("下载文件出错");
			}finally{
				try {
					if(os != null){
						os.close();
					}
					if(is != null){
						is.close();
					}
				} catch (IOException e) {
				}
			}
		}else{
			throw new Exception("下载文件请返回File类型的对象");
		}
		
		return null;
	}

}
